package org.support.small.infrastructure.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mybatisflex.annotation.TableRef;
import com.mybatisflex.core.query.QueryOrderBy;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.query.SqlOperators;
import com.mybatisflex.core.table.TableInfo;
import com.mybatisflex.core.table.TableInfoFactory;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.Map;
import java.util.Objects;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class WebUtils {
    public static QueryWrapper createQuery(Object entity, SqlOperators operators, QueryOrderBy... orderBy) {
        TableRef tableRef = entity.getClass().getAnnotation(TableRef.class);

        TableInfo tableInfo = TableInfoFactory.ofEntityClass(Objects.nonNull(tableRef) ? tableRef.value() : entity.getClass());
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> map = objectMapper.convertValue(entity, new TypeReference<>() {
        });
        return tableInfo.buildQueryWrapper(map, operators).orderBy(orderBy);
    }

    public static QueryWrapper createQuery(Object entity, QueryOrderBy... orderBy) {
        return createQuery(entity, SqlOperators.empty()).orderBy(orderBy);
    }
}
